<?php

class GameboardController extends Controller
{
	const MAKE_MOVE = "makemove";

	public function DoControll()
	{
		$this->Title( 'Game: ' . $this->view->GetGameID() );
		
		$this->CSS( "gameboard" );

		$this->JS( "game/engine" );
		$this->JS( "game/map" );
		$this->JS( "game/tile" );
		$this->JS( "game/game" );
		$this->JS( "game/player" );
		$this->JS( "game/robot" );
		$this->JS( "game/register" );
		$this->JS( "game/registerdeck" );
		$this->JS( "game/gameview" );
		$this->JS( "game/positiondata" );
		$this->JS( "game/conveyorhelpdata" );
		$this->JS( "game/registerview" );
		$this->JS( "game/turnmovementcollection" );
		$this->JS( "game/run" );

		if ( Auth::IsLoggedIn() )
		{
			if ( ( $game = $this->model->GetGame( $this->view->GetGameID() ) ) )
			{
				$self = null;

				foreach ( $game->Players() as $player )
				{
					if ( $player->User()->ID() == Auth::GetUser()->ID() )
					{
						$self = $player;
					}
				}

				if ( $this->view->GetAction() == self::MAKE_MOVE )
				{
					try
					{
						$this->model->MakeMove( $game, $self, $this->view->GetRegisterCards() );
					}
					catch ( Exception $e )
					{
						$this->view->Error( $e->getMessage() );
					}
				}

				if ( $this->model->ReadyCheck( $game ) )
				{
					require_once 'php/game/Engine.php';
					$engine = new game\Engine( $game );
					$engine->DoMajorCycle();

					try
					{
							$this->model->PrepareNextTurn( $game, $engine->m_currentGame );
					}
					catch ( Exception $e )
					{
						$this->view->Error( "Failed preparing next turn." );
					}

					$game = $this->model->GetGame( $game->ID() );

					// Pusha!
				}

				$this->IJS( "window.onload = function() { run( " . $game->ID() . ", \"" . $game->Map()->Tiles() . "\", [" );

				$nPlayers = count( $game->Players() );

				foreach ( $game->Players() as $player )
				{
					$this->IJS( '{  "playerID": ' . $player->User()->ID() . ',
									"playerName": "' . $player->User()->Name() . '",
									"posX" : "' . $player->Robot()->PosX() . '",
									"posY" : "' . $player->Robot()->PosY() . '",
									"direction": "' . $player->Robot()->Direction() . '",
									"robotType": ' . $player->Robot()->RobotTypeID() . ',
									"cards": ' . ( ( $player->User()->ID() == Auth::GetUser()->ID() ) ? '"' . $player->Cards() . '"' : '""' ) . ',
									"self": ' . ( ( $player->User()->ID() == Auth::GetUser()->ID() ) ? 'true' : 'false' ) . ' }' );
					if ( --$nPlayers > 0 )
					{
						$this->IJS( "," );
					}
				}

				$this->IJS( "] ) };" );

				$this->view->BuildGameboard();
			}

		}
		else
		{
			$this->view->Error( "You are not logged in." );
		}

		$this->view->PrintErrors( '<p class="error"><span>Error:</span> _ERROR_</p>' );
		$this->view->PrintMessages( '<p class="message"><span>Success:</span> _MESSAGE_</p>' );
	}
}
